import { ADD_ITEM, DEL_ITEM, 
    REMOVE_ITEM, 
    CHANGE_ITEM_CHECKED, 
    CHANGE_CHECK } from '../actions/car'
import fn from '../../utils'

let obj = {
    list: [],
    allCount: 0,
    allPrice: 0,
    flag: true
}

function car(state = obj, action) {
    let NewState = JSON.parse(JSON.stringify(state))
    switch (action.type) {
        case ADD_ITEM:
            // 没有的话添加 
            let isExist = NewState.list.some(item => item.id === action.item.id)
            if (!isExist) {
                NewState.list.push(action.item)
            } else {
                let index = NewState.list.findIndex(item => item.id === action.item.id)
                NewState.list[index].count += 1
            }
            fn(NewState)
            return NewState
        case DEL_ITEM:
            NewState.list[action.index].count -= 1
            fn(NewState)
            return NewState
        case REMOVE_ITEM:
            NewState.list.splice(action.index, 1)
            fn(NewState)
            return NewState
        case CHANGE_ITEM_CHECKED:
            NewState.flag  = action.checked
            NewState.list.forEach(item => item.isCheck = action.checked)
            fn(NewState)
            return NewState
        case CHANGE_CHECK:
            NewState.list[action.index].isCheck = !NewState.list[action.index].isCheck
            NewState.flag = NewState.list.every(item => item.isCheck)
            // let flag = NewState.list.every(item => item.isCheck)
            // sessionStorage.setItem('flag', flag)
            fn(NewState)
            return NewState
        default:
            return state
    }
}

export default car